package com.woniuxy.house.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.Constants;
import com.woniuxy.house.exception.CaptchaMistakeException;
import com.woniuxy.house.utils.RequestThreadLocalCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StreamUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 验证码过滤器
 * @author baobo
 * @date 2022-08-19-11:20
 */
public class CaptchaFilter extends OncePerRequestFilter {
	@Autowired
	private ObjectMapper objectMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.debug("in-----CaptchaFilter");
        //过滤路径,如果是/portal/tologin,则校验，否则放行
		//ServletInputStream s=new
		//获取请求参数,并转换成字符串存储在ThreadLocal

        if("/api/user/login".equals(request.getRequestURI())&&"post".equalsIgnoreCase(request.getMethod())){
			byte[] bytes = StreamUtils.copyToByteArray(request.getInputStream());
			String params = new String(bytes, request.getCharacterEncoding());
			RequestThreadLocalCache.setRequestToThreadLocal(params);
        	//得到用户输入的验证码
			Map<String,String> map = objectMapper.readValue(params, Map.class);
            String key=map.get("key");
            String captcha = stringRedisTemplate.opsForValue().get(key);
            String code = map.get("code");
            //得到session存储的验证码,
            //String captcha = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if(!code.equalsIgnoreCase(captcha)){
             //验证码不相同，直接返回
                authenticationFailureHandler.onAuthenticationFailure(request,response,new CaptchaMistakeException("验证码错误"));
                return;
            }
        }
        filterChain.doFilter(request,response);

    }
}
